/**
 * Copyright 2013 Net355 Co,.Ltd. 
 * All rights reserved.
 *
 * "AjaxController.java is for what: "
 * 
 * Create by Ray at 2013-12-24 下午1:53:38.
 * Ray [email:rayinhangzhou@126.com]
 * 
 * Revision History
 *
 * Date            Programmer                   Notes
 * ---------    ---------------------  -----------------------------------
 * 2013-12-24            Ray                       initial
 **/


package com.net355.eblog.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.net355.eblog.models.EbChat;
import com.net355.eblog.models.EbNotebook;
import com.net355.eblog.models.EbTag;
import com.net355.eblog.util.CacheHelper;
import com.net355.eblog.util.DataHelper;
import com.net355.eblog.util.ExecuteResult;
import com.net355.eblog.util.GlobalParams;
import com.net355.eblog.util.StaticHtmlHelper;
import com.net355.eblog.util.StringUtil;

/**
 * ajax请求模块
 * @author ray
 *
 */
@Controller
public class AjaxController extends BaseController {
	private static Log LOG = LogFactory.getLog(AjaxController.class);

	@RequestMapping(value="/ajax/notebooklist")
	public @ResponseBody
	ExecuteResult listNotebook() {
		try {
			return new ExecuteResult(true, StaticHtmlHelper.getBookList());
		} catch (Exception e) {
			LOG.error("listNotebook error--->>>", e);
			return new ExecuteResult(false, GlobalParams.ERR_DESC);
		}
	}

	@RequestMapping(value="/ajax/summarylist")
	public @ResponseBody
	ExecuteResult listSummary() {
		try {
			return new ExecuteResult(true, StaticHtmlHelper.getSummaryList());
		} catch (Exception e) {
			LOG.error("listSummary error--->>>", e);
			return new ExecuteResult(false, GlobalParams.ERR_DESC);
		}
	}
	
	@RequestMapping(value="/ajax/notebook")
	public @ResponseBody
	ExecuteResult listNoteByNotebook(
			@RequestParam(value = "notebook", required = true) String notebookGuid,
			@RequestParam(value = "pageIndex", required = true) int pageIndex) {
		try {
			EbNotebook notebook = (EbNotebook)CacheHelper.get_cache(notebookGuid);
			String noteList = StaticHtmlHelper.getNoteListByNoteGuids(notebook.getNotes(), (pageIndex-1)*GlobalParams.PAGE_SIZE, GlobalParams.PAGE_SIZE);
			return new ExecuteResult(true, noteList, notebook.getNotes().size());
		} catch (Exception e) {
			LOG.error("listNoteByNotebook error--->>>", e);
			return new ExecuteResult(false, GlobalParams.ERR_DESC);
		}
	}
	
	@RequestMapping(value="/ajax/notechat")
	public @ResponseBody
	ExecuteResult listChatByNote(
			@RequestParam(value = "note", required = true) String noteGuid,
			@RequestParam(value = "offset", required = true) int offset,
			@RequestParam(value = "size", required = true) int size) {
		try {
			List<EbChat> chatList = DataHelper.getChatListByNote(noteGuid, offset, size);
			return new ExecuteResult(true, null, chatList);
		} catch (Exception e) {
			LOG.error("listChatByNote error--->>>", e);
			return new ExecuteResult(false, GlobalParams.ERR_DESC);
		}
	}

	@RequestMapping(value="/ajax/comment")
	@SuppressWarnings("unchecked")
	public @ResponseBody
	ExecuteResult addNoteChat(
			@RequestParam(value = "note", required = true) String noteGuid,
			@RequestParam(value = "name", required = true) String name,
			@RequestParam(value = "content", required = true) String content,
			@RequestParam(value = "reply", required = true) String reply) {
		try {
			EbChat chat = new EbChat();
			if(!StringUtil.isEmpty(reply)) {
				EbChat father = (EbChat)CacheHelper.get_cache(reply);
				if(!father.getNoteGuid().equals(noteGuid)) {
					return new ExecuteResult(false, GlobalParams.ERR_DESC);
				}
				chat.setFatherGuid(reply);
			}
			chat.setGuid(UUID.randomUUID().toString());
			chat.setNoteGuid(noteGuid);
			chat.setName(StringUtil.parseHTMLtoText(name));
			chat.setContent(StringUtil.transHtml(content));
			chat.setIp(getRequest().getRemoteAddr());
			chat.setCreateTime(System.currentTimeMillis());
			CacheHelper.set_cache(chat.getGuid(), chat);
			chat.setFatherChat((EbChat)CacheHelper.get_cache(reply));
			List<String> chats = (List<String>) CacheHelper.get_cache(noteGuid+GlobalParams.CACHE_NAME_LIST_NOTE_COMMENT);
			chats.add(chat.getGuid());
			CacheHelper.set_cache(noteGuid+GlobalParams.CACHE_NAME_LIST_NOTE_COMMENT, chats);
			GlobalParams.COUNT_CHAT.incrementAndGet();
			return new ExecuteResult(true, null, chat);
		} catch (Exception e) {
			LOG.error("addNoteChat error--->>>", e);
			return new ExecuteResult(false, GlobalParams.ERR_DESC);
		}
	}

	
	@RequestMapping(value="/ajax/syschat")
	public @ResponseBody
	ExecuteResult listChat(
			@RequestParam(value = "pageIndex", required = true) int pageIndex) {
		try {
			List<EbChat> chatList = DataHelper.getChatList((pageIndex-1)*GlobalParams.PAGE_SIZE, GlobalParams.PAGE_SIZE);
			return new ExecuteResult(true, null, chatList);
		} catch (Exception e) {
			LOG.error("listChat error--->>>", e);
			return new ExecuteResult(false, GlobalParams.ERR_DESC);
		}
	}

	@RequestMapping(value="/ajax/chat")
	@SuppressWarnings("unchecked")
	public @ResponseBody
	ExecuteResult addSysChat(
			@RequestParam(value = "name", required = true) String name,
			@RequestParam(value = "content", required = true) String content,
			@RequestParam(value = "reply", required = true) String reply) {
		try {
			EbChat chat = new EbChat();
			if(!StringUtil.isEmpty(reply)) {
				EbChat father = (EbChat)CacheHelper.get_cache(reply);
				if(father==null) {
					return new ExecuteResult(false, GlobalParams.ERR_DESC);
				}
				chat.setFatherGuid(reply);
			}
			name = StringUtil.isEmpty(name)?"匿名":name;
			chat.setGuid(UUID.randomUUID().toString());
			chat.setName(StringUtil.parseHTMLtoText(name));
			if(GlobalParams.BLOG_OWNER.equals(name)) {
				chat.setName("<font style=\"color:#D44; font-weight:bold;\">博主</font>");
			}
			chat.setContent(StringUtil.transHtml(content));
			chat.setIp(getRequest().getRemoteAddr());
			chat.setCreateTime(System.currentTimeMillis());
			CacheHelper.set_cache(chat.getGuid(), chat);
			chat.setFatherChat((EbChat)CacheHelper.get_cache(reply));
			List<String> chats = (List<String>) CacheHelper.get_cache(GlobalParams.CACHE_NAME_LIST_CHAT_SYSTEM);
			chats.add(chat.getGuid());
			CacheHelper.set_cache(GlobalParams.CACHE_NAME_LIST_CHAT_SYSTEM, chats);
			GlobalParams.COUNT_CHAT.incrementAndGet();
			return new ExecuteResult(true, null, chat);
		} catch (Exception e) {
			LOG.error("addSysChat error--->>>", e);
			return new ExecuteResult(false, GlobalParams.ERR_DESC);
		}
	}
	
	@RequestMapping(value="/ajax/tag")
	public @ResponseBody
	ExecuteResult listNoteByTag(
			@RequestParam(value = "tag", required = true) String tagGuid,
			@RequestParam(value = "pageIndex", required = true) int pageIndex) {
		try {
			EbTag tag = (EbTag)CacheHelper.get_cache(tagGuid);
			String noteList = StaticHtmlHelper.getNoteListByNoteGuids(tag.getNotes(), (pageIndex-1)*GlobalParams.PAGE_SIZE, GlobalParams.PAGE_SIZE);
			return new ExecuteResult(true, noteList, tag.getNotes().size());
		} catch (Exception e) {
			LOG.error("listNoteByTag error--->>>", e);
			return new ExecuteResult(false, GlobalParams.ERR_DESC);
		}
	}

	
	@RequestMapping(value="/ajax/search")
	@SuppressWarnings("unchecked")
	public @ResponseBody
	ExecuteResult listNoteBySearch(
			@RequestParam(value = "key", required = true) String match,
			@RequestParam(value = "offset", required = true) int offset,
			@RequestParam(value = "size", required = true) int size) {
		try {
			if(StringUtil.isEmpty(match)) {
				List<String> notes = (List<String>) CacheHelper.get_cache(GlobalParams.CACHE_NAME_LIST_NOTE);
				return StaticHtmlHelper.getNoteListByNoteGuidsAndMatch(notes, null, offset, size);
			} else {
				GlobalParams.COUNT_SEARCH.incrementAndGet();
				List<String> notes = (List<String>) CacheHelper.get_cache(GlobalParams.CACHE_NAME_LIST_NOTE);
				return StaticHtmlHelper.getNoteListByNoteGuidsAndMatch(notes, match.toLowerCase(), offset, size);
			}
		} catch (Exception e) {
			LOG.error("listNoteByNotebook error--->>>", e);
			return new ExecuteResult(false, GlobalParams.ERR_DESC);
		}
	}
	
	@RequestMapping(value="/ajax/gameStart", method = RequestMethod.POST)
	public @ResponseBody
	ExecuteResult gameStart() {
		try {
			String md5 = UUID.randomUUID().toString();
			CacheHelper.set_cache("game_"+md5, System.currentTimeMillis(), 60, 0);
			return new ExecuteResult(true, md5);
		} catch (Exception e) {
			LOG.error("gameStart error--->>>", e);
			return new ExecuteResult(false, GlobalParams.ERR_DESC);
		}
	}
	
	@RequestMapping(value="/ajax/gameCheck", method = RequestMethod.POST)
	public @ResponseBody
	ExecuteResult gameCheck(
			@RequestParam(value = "md5", required = true) String md5) {
		try {
			CacheHelper.get_cache("game_"+md5);
			return new ExecuteResult(true, null);
		} catch (Exception e) {
			LOG.error("gameCheck error--->>>", e);
			return new ExecuteResult(false, GlobalParams.ERR_DESC);
		}
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/ajax/gameEnd", method = RequestMethod.POST)
	public @ResponseBody
	ExecuteResult gameEnd(
			@RequestParam(value = "md5", required = true) String md5,
			@RequestParam(value = "name", required = true) String name,
			@RequestParam(value = "score", required = true) String score) {
		try {
			Long timestamp = (Long) CacheHelper.get_cache("game_"+md5);
			if(timestamp==null) {
				return new ExecuteResult(false, "你好像有作弊哦！");
			}
			float _score = Float.parseFloat(score);
			long interval = System.currentTimeMillis()-timestamp;
			if(_score*1000>=interval+2000) {
				return new ExecuteResult(false, "你好像有作弊哦！");
			}
			CacheHelper.remove_cache("game_"+md5);
			List<String> scoreList = (List<String>) CacheHelper.get_cache(GlobalParams.CACHE_NAME_LIST_GAME_SCORE);
			if(scoreList.isEmpty()) {
				scoreList.add(name+"_"+score);
				CacheHelper.set_cache(GlobalParams.CACHE_NAME_LIST_GAME_SCORE, scoreList);
				return new ExecuteResult(true, null, scoreList);
			}
			boolean isAdd = false;
			List<String> newScoreList = new ArrayList<>();
			for (int i = 0; i < scoreList.size(); i++) {
				if(isAdd) {
					newScoreList.add(scoreList.get(i-1));
					continue;
				}
				String[] person_score = scoreList.get(i).split("_");
				if(_score>Float.parseFloat(person_score[1])) {
					newScoreList.add(name+"_"+score);
					isAdd = true;
				} else {
					newScoreList.add(scoreList.get(i));
				}
			}
			if(newScoreList.size()<8) {
				if(isAdd) {
					newScoreList.add(scoreList.get(scoreList.size()-1));
				} else {
					newScoreList.add(name+"_"+score);
				}
			}
			CacheHelper.set_cache(GlobalParams.CACHE_NAME_LIST_GAME_SCORE, newScoreList);
			return new ExecuteResult(true, null, newScoreList);
		} catch (Exception e) {
			LOG.error("gameEnd error--->>>", e);
			return new ExecuteResult(false, GlobalParams.ERR_DESC);
		}
	}
	
	@RequestMapping(value="/ajax/gameScoreList")
	public @ResponseBody
	ExecuteResult listGameScore() {
		try {
			List<?> list = (List<?>) CacheHelper.get_cache(GlobalParams.CACHE_NAME_LIST_GAME_SCORE); 
			return new ExecuteResult(true, null, list);
		} catch (Exception e) {
			LOG.error("listGameScore error--->>>", e);
			return new ExecuteResult(false, GlobalParams.ERR_DESC);
		}
	}
	
	
	
	
	
	
	
	
	
}
